﻿//<my-matriculator - a simple tool for registering racers in a USAC cyclocross race>
//Copyright (C) <2011>  <Steven Rivers>

//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.

//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.

//You should have received a copy of the GNU General Public License
//along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Linq;
using System.Text;
using System.Data;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.IO;
using System.Windows.Media.Imaging;
using Registration.Model;
using Registration.Model.Entities;
using Registration.Printing;


namespace Registration
{
    /// <summary>
    /// Interaction logic for ResultsWindow.xaml
    /// </summary>
    public partial class ResultsWindow
    {
        public ResultsWindow()
        {
            InitializeComponent();
            cmbField.ItemsSource = FieldsDb.GetAllFields();
            Refresh(-1);

            var myBrush = new ImageBrush {ImageSource = new BitmapImage(new Uri("./background.jpg", UriKind.Relative))};
            Background = myBrush;

            Opacity = .98;

        }


        private void OnBibKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Enter) return;
            var field = (Field)cmbField.SelectedItem;
            if ( field != null )
            {
                int bib;
                Int32.TryParse(txtBibNumber.Text, out bib);
                var entry = EntryDb.FindEntryByBib(bib, field.FieldId);
                if (entry != null)
                {
                    AddResult(field.FieldId, entry);
                }
                else
                {
                    var entries = EntryDb.GetEntriesForBib(bib);
                    if (entries.Count == 0)
                    {
                        MessageBox.Show("Bib Number Not Found!", "Error");
                    }
                    else
                    {
                        var window = new ResultConflict(bib, entries);
                        window.ShowDialog();
                        entry = window.SelectedEntry;
                        if (entry != null)
                        {
                            AddResult(field.FieldId, entry);
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("Select Field First");
            }

            e.Handled = true;
        }

        private void AddResult(int fieldid, Entry entry)
        {
            var categoryplace = ResultsDb.GetPlaceInCategory(fieldid, entry.CategoryName);
            var overallplace = 1 + ResultsDb.GetResultsForField(fieldid).Count;

            var result = new Result(overallplace, categoryplace, entry.Bib, entry.License, fieldid, entry.CategoryName, entry.FirstName, entry.LastName, entry.Club);

            if (!ResultsDb.IsAlreadyInField(fieldid, result))
            {
                ResultsDb.AddResult(result);
                txtBibNumber.Text = "";
                txtBibNumber.Focus();
                Refresh();
            }
            else
            {
                MessageBox.Show("Duplicate Bib In Field", "Error");
            }

        }

        private void OnComboChanged(object sender, EventArgs e)
        {
            Refresh();
        }

        private void Refresh()
        {
            var f = ((Field)cmbField.SelectedItem);
            if (f != null)
                Refresh(f.FieldId);
        }

        private void Refresh(int fieldid)
        {
            var results = ResultsDb.GetResultsForField(fieldid);
            listResults.ItemsSource = results;
        }

        private void ListResultsKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Delete) return;
            ResultsDb.DeleteLast();
            Refresh();
        }

        private void OnPrintButton(object sender, RoutedEventArgs e)
        {
            var f = (Field)cmbField.SelectedItem;
            if (f == null) return;
            var results = ResultsDb.GetResultsForField(f.FieldId);
            var table = CollectionHelper.ConvertTo(results);

            var printDialog = new PrintDialog();
            if (printDialog.ShowDialog() != true) return;
            var paginator = new ResultDataSetPaginator(results, table,
                                                       new Typeface(GlobalData.FontName), GlobalData.FontSize, 96 * 0.75,
                                                       new Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight));

            printDialog.PrintDocument(paginator, "RaceResults For-xyz");
        }

        private void OnExportButton(object sender, RoutedEventArgs e)
        {
            var dlg = new Microsoft.Win32.SaveFileDialog { DefaultExt = ".csv", Filter = "CSV Files (.csv)|*.csv" };
            var result = dlg.ShowDialog();
            if (result == false) return;

            var sb = new StringBuilder();
            var dt = ResultsDbDataset.ReadDataSet().Tables["Result"];
            var columnNames = dt.Columns.Cast<DataColumn>().Select(column => column.ColumnName).ToArray();
            sb.AppendLine(string.Join(",", columnNames));

            foreach (var fields in from DataRow row in dt.Rows select row.ItemArray.Select(field => field.ToString()).ToArray())
            {
                sb.AppendLine(string.Join(",", fields));
            }

            File.WriteAllText(dlg.FileName, sb.ToString());
        }


        private void OnResolve(object sender, RoutedEventArgs e)
        {
            var field = (Field)cmbField.SelectedItem;

            if (field == null) return;
            var results = ResultsDb.GetResultsForField(field.FieldId);
            var entries = EntryDb.GetAllEntriesForField(field.FieldId);

            var bibs = from r in results select r.BibNumber;
            var matches = from entry in entries where !bibs.Contains(entry.Bib) select entry;

            foreach (var result in matches.Select(entry => 
                new Result(999, 999, entry.Bib, entry.License, field.FieldId, entry.CategoryName, entry.FirstName, entry.LastName, entry.Club)))
            {
                ResultsDb.AddResult(result);
            }

            Refresh();
        }
    }
}

